package com.jiawa.train.gateway.config;

import com.jiawa.train.gateway.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class LoginMemberFilter implements GlobalFilter, Ordered {
    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       //1.先获取请求的路径
        String path = exchange.getRequest().getURI().getPath();
        //2.排除不需要验证的路径
        if(path.contains("/member/member/login")
                || path.contains("/member/member/send-code")
                || path.contains("/admin")
                || path.contains("/business/kaptcha")) {
            log.info("不需要验证的路径：{}", path);
            return chain.filter(exchange); //直接放行
        }
        //3.获取请求头中的token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if(token ==null || token.isBlank()) {
            log.error("token为空,请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete(); //结束请求
        }
        //4.验证token
        boolean validate = JwtUtil.validate(token);
        if(validate) {
            //如果验证通过 - 未过期且正确->放行
            log.info("token验证通过,放行");
            return chain.filter(exchange);
        }else{
            log.error("token验证未通过,请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED );
            return exchange.getResponse().setComplete();
        }
    }
}
